﻿using System;
using System.Reflection;
using System.Runtime.Serialization;
using Skyline;
using SmartQuant;

namespace QuantBox
{
    public static class ExecutionMessageExtensions
    {
        private static readonly FastFieldInfo<ExecutionCommand, byte>? CommandProviderIdField;
        private static readonly FastFieldInfo<ExecutionReport, byte>? ReportProviderIdField;

        private static FieldInfo? GetDataMemberField(IReflect type, string name)
        {
            foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
            {
                try
                {
                    var member = field.GetCustomAttribute<DataMemberAttribute>();
                    if (member != null && member.Name == name)
                    {
                        return field;
                    }
                }
                catch (Exception)
                {
                    //ignore
                }
            }

            return null;
        }

        static ExecutionMessageExtensions()
        {
            var field = GetDataMemberField(typeof(ExecutionCommand), "providerId");
            if (field != null)
            {
                CommandProviderIdField = new FastFieldInfo<ExecutionCommand, byte>(field);
            }
            field = GetDataMemberField(typeof(ExecutionReport), "providerId");
            if (field != null)
            {
                ReportProviderIdField = new FastFieldInfo<ExecutionReport, byte>(field);
            }
        }

        public static void SetProviderId(this ExecutionCommand command, byte providerId)
        {
            CommandProviderIdField?.Setter(command, providerId);
            if (command.Order != null)
                command.Order.ProviderId = providerId;
        }

        public static void SetProviderId(this ExecutionReport report, byte providerId)
        {
            ReportProviderIdField?.Setter(report, providerId);
            if (report.Order != null)
                report.Order.ProviderId = providerId;
        }
    }
}